package router

import (
	"context"
	"log"
	"net/http"
	"path"
	"time"

	"gateway/public"

	"github.com/gin-gonic/gin"
)

var (
	SrvHandler *http.Server
)

func ServerRun() {
	gin.SetMode(public.BaseConf.GetString("base.debug_mode"))
	r := InitRouter()
	SrvHandler = &http.Server{
		Addr:           public.BaseConf.GetString("http.addr"),
		Handler:        r,
		ReadTimeout:    time.Duration(public.BaseConf.GetInt("http.read_timeout")) * time.Second,
		WriteTimeout:   time.Duration(public.BaseConf.GetInt("http.write_timeout")) * time.Second,
		MaxHeaderBytes: 1 << uint(public.BaseConf.GetInt("http.max_header_bytes")),
	}
	go func() {
		env := public.BaseConf.GetString("base.env")
		if env == "dev" {
			log.Printf(" [INFO] HttpServerRun:%s\n", public.BaseConf.GetString("http.addr"))
			if err := SrvHandler.ListenAndServe(); err != nil {
				log.Fatalf(" [ERROR] HttpServerRun:%s err:%v\n", public.BaseConf.GetString("http.addr"), err)
			}
		} else if env == "prod" {
			// 不同系统的路径分隔符不同，注意路径问题
			log.Printf(" [INFO] HttpsServerRun:%s\n", public.BaseConf.GetString("http.addr"))
			pemPath := path.Join("cert_file", "server.pem")
			keyPath := path.Join("cert_file", "server.key")
			if err := SrvHandler.ListenAndServeTLS(pemPath, keyPath); err != nil {
				log.Fatalf(" [ERROR] HttpsServerRun:%s err:%v\n", public.BaseConf.GetString("http.addr"), err)
			}
		}
	}()
}

func ServerStop() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := SrvHandler.Shutdown(ctx); err != nil {
		log.Fatalf(" [ERROR] HttpServerStop err:%v\n", err)
	}
	log.Printf(" [INFO] HttpServerStop stopped\n")
}
